<template>
  <div class="order-detail-container">
    <!-- 顶部导航 -->
    <el-header class="order-header">
      <div class="header-back" @click="router.go(-2)">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title">订单详情</div>
    </el-header>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>加载中...</span>
    </div>

    <!-- 订单内容 -->
    <template v-else>
      <!-- 订单状态 -->
      <div class="order-status" :class="statusClass">
        <el-icon :class="statusIconClass">
          <component :is="statusIcon" />
        </el-icon>
        <span class="status-text">{{ statusText }}</span>
        <div class="status-desc">{{ statusDesc }}</div>
      </div>

      <!-- 收货地址 -->
      <div class="address-section">
        <div class="address-info">
          <el-icon><Location /></el-icon>
          <div class="address-details">
            <div class="receiver">
              <span>{{ userInfo.username }}</span>
              <span>{{ orderDetail.phone }}</span>
            </div>
            <div class="address">{{ orderDetail.address }}</div>
          </div>
        </div>
      </div>

      <!-- 商家信息 -->
      <div class="merchant-info">
        <img :src="getImageUrl(orderDetail.merchantAvatar)" class="merchant-avatar">
        <span class="merchant-name">{{ orderDetail.merchantName }}</span>
      </div>

      <!-- 商品列表 -->
      <div class="item-list">
        <div v-for="item in orderDetail.items" :key="item.dishId" class="order-item">
          <div class="item-name">{{ item.name }}</div>
          <div class="item-quantity">x{{ item.quantity }}</div>
          <div class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
        </div>
      </div>

      <!-- 费用明细 -->
      <div class="order-summary">
        <div class="summary-row">
          <span>商品总价</span>
          <span>¥{{ subtotal.toFixed(2) }}</span>
        </div>
        <div class="summary-row">
          <span>配送费</span>
          <span>¥{{ (orderDetail.deliveryfee||0).toFixed(2) }}</span>
        </div>
        <div class="summary-row total">
          <span>实付款</span>
          <span class="total-price">¥{{ orderDetail.totalPrice.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="order-info-section">
        <h3 class="section-title">订单信息</h3>
        <div class="info-row">
          <span class="label">订单编号</span>
          <span class="value">{{ orderDetail.orderNo }}</span>
        </div>
        <div class="info-row">
          <span class="label">下单时间</span>
          <span class="value">{{ formatTime(orderDetail.createTime) }}</span>
        </div>
        <div class="info-row" v-if="orderDetail.payTime">
          <span class="label">支付时间</span>
          <span class="value">{{ formatTime(orderDetail.payTime) }}</span>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-buttons" v-if="orderDetail.status === 1">
        <el-button type="primary" @click="handlePay">立即支付</el-button>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  ArrowLeft,
  Location,
  Loading,
  CircleCheckFilled,
  Clock,
  CloseBold
} from '@element-plus/icons-vue';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import { useCookies } from 'vue3-cookies';
import { ElMessage } from 'element-plus';

const { cookies } = useCookies();
const route = useRoute();
const router = useRouter();

// 订单数据
const orderDetail = ref({
  orderNo: '',
  status: 0,
  createTime: null,
  payTime: null,
  totalPrice: 0,
  deliveryfee: 0,
  address: '',
  phone: '',
  merchantId: 0,
  merchantName: '',
  merchantAvatar: '',
  items: []
});

const loading = ref(true);

// 用户信息
const userInfo = ref({
  username: cookies.get('username') || '未设置'
});

// 计算属性
const subtotal = computed(() => {
  return orderDetail.value.items.reduce(
    (sum, item) => sum + (item.price * item.quantity), 
    0
  );
});

const statusText = computed(() => {
  const statusMap = {
    1: '待支付',
    2: '已支付',
    3: '配送中',
    4: '已完成'
  };
  return statusMap[orderDetail.value.status] || '未知状态';
});

const statusDesc = computed(() => {
  const descMap = {
    1: '请尽快完成支付',
    2: '商家已接单，正在准备中',
    3: '骑手正在配送中',
    4: '订单已完成'
  };
  return descMap[orderDetail.value.status] || '';
});

const statusClass = computed(() => {
  return {
    'status-pending': orderDetail.value.status === 1,
    'status-paid': orderDetail.value.status === 2,
    'status-delivering': orderDetail.value.status === 3,
    'status-completed': orderDetail.value.status === 4
  };
});

const statusIcon = computed(() => {
  const iconMap = {
    1: Clock,
    2: CircleCheckFilled,
    3: CircleCheckFilled,
    4: CircleCheckFilled
  };
  return iconMap[orderDetail.value.status] || CloseBold;
});

const statusIconClass = computed(() => {
  return {
    'icon-pending': orderDetail.value.status === 1,
    'icon-paid': orderDetail.value.status === 2,
    'icon-delivering': orderDetail.value.status === 3,
    'icon-completed': orderDetail.value.status === 4
  };
});

// 方法
const getImageUrl = (path) => {
  if (!path) return '';
  return `${import.meta.env.VITE_API_BASE_URL}${path}`;
};

const formatTime = (timeStr) => {
  if (!timeStr) return '--';
  return new Date(timeStr).toLocaleString();
};

const fetchOrderDetail = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/order/detail`, {
      params: { orderId: route.params.orderId }
    });
    orderDetail.value = response.data;
    console.log(orderDetail.value.deliveryfee+"  "+response.data.deliveryfee)
  } catch (error) {
    ElMessage.error('获取订单详情失败');
    console.error('Error fetching order detail:', error);
  } finally {
    loading.value = false;
  }
};

const handlePay = () => {
  router.push({
    path: `/order/confirm/${orderDetail.value.merchantId}`,
    query: {
      merchantName: orderDetail.value.merchantName,
      merchantAvatar: orderDetail.value.merchantAvatar,
      deliveryFee: orderDetail.value.deliveryFee,
      selectedFoods: JSON.stringify(
        orderDetail.value.items.map(item => ({
          dishId: item.dishId,
          name: item.name,
          price: item.price,
          count: item.quantity
        }))
      )
    }
  });
};

onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped>
.order-detail-container {
  padding-bottom: 80px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.order-header {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 50px;
  border-bottom: 1px solid #eee;
}

.header-back {
  margin-right: 10px;
  cursor: pointer;
  font-size: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-icon {
  font-size: 40px;
  margin-bottom: 10px;
  animation: rotating 2s linear infinite;
}

.order-status {
  padding: 20px;
  text-align: center;
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
}

.status-text {
  display: block;
  margin-top: 10px;
  font-size: 18px;
  font-weight: bold;
}

.status-desc {
  margin-top: 5px;
  font-size: 14px;
  color: #666;
}

.status-pending {
  color: #e6a23c;
}

.status-paid {
  color: #409eff;
}

.status-delivering {
  color: #67c23a;
}

.status-completed {
  color: #909399;
}

.icon-pending {
  color: #e6a23c;
  font-size: 40px;
}

.icon-paid {
  color: #409eff;
  font-size: 40px;
}

.icon-delivering {
  color: #67c23a;
  font-size: 40px;
}

.icon-completed {
  color: #909399;
  font-size: 40px;
}

.address-section {
  background-color: #fff;
  padding: 15px;
  margin: 10px;
  border-radius: 8px;
}

.address-info {
  display: flex;
  align-items: center;
}

.address-info .el-icon {
  font-size: 20px;
  color: #ff5339;
  margin-right: 10px;
}

.address-details {
  flex: 1;
}

.receiver {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.receiver span:first-child {
  margin-right: 15px;
  font-weight: bold;
}

.address {
  font-size: 14px;
  color: #666;
}

.merchant-info {
  display: flex;
  align-items: center;
  padding: 15px;
  margin: 10px;
  background-color: #fff;
  border-radius: 8px;
}

.merchant-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.merchant-name {
  font-size: 16px;
  font-weight: bold;
}

.item-list {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.item-name {
  flex: 1;
}

.item-quantity {
  width: 50px;
  text-align: center;
}

.item-price {
  width: 80px;
  text-align: right;
}

.order-summary {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.summary-row.total {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
  font-weight: bold;
}

.total-price {
  color: #ff5339;
  font-size: 18px;
}

.order-info-section {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
}

.section-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.label {
  color: #999;
}

.value {
  color: #333;
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.action-buttons .el-button {
  width: 90%;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 25px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>